package main

import (
	"encoding/csv"
	"fmt"
	"os"
	"strconv"
)

type Post struct {
	Id int
	Content string
	Author string
}

func main() {
	//创建一个writer
	csvFile, _ := os.Create("post.csv")
	defer csvFile.Close()

	allPost := []Post{
		{Id:1, Content:"Hello", Author:"Tom"},
		{Id:2, Content:"world", Author:"Aim"},
		{Id:3, Content:"testaa", Author:"Aim"},
		{Id:4, Content:"testaa", Author:"Tom"},
		{Id:5, Content:"testaa", Author:"Tom"},
	}

	writer := csv.NewWriter(csvFile)

	for _, val := range allPost{
		line := []string{strconv.Itoa(val.Id), val.Content, val.Author}
		err := writer.Write(line)
		if err != nil {
			fmt.Println(err)
		}
	}
	//因为下面紧接着会读取文件内容为了避免数据还在缓存区中，先进行刷新一下，保证数据全部写入文件
	writer.Flush()

	//读取CSV文件
	file, _ := os.Open("post.csv")
	defer  file.Close()

	//创建一个读取器
	reader := csv.NewReader(file)
	// -1 读取器发现记录里缺少字段，程序不会中断
	// 0 读取器以读取到的第一条记录为标准
	// >0 字段必须符合指定的数量，不然就报错
	reader.FieldsPerRecord = 0
	record, err := reader.ReadAll()
	if err != nil {
		panic(err)
	}

	var Posts []Post
	for _, line := range record {
		id, _ := strconv.ParseInt(line[0], 0, 0)
		post := Post{Id:int(id), Content:line[1], Author:line[2]}
		Posts = append(Posts, post)
	}

	for _, line1 := range Posts {
		fmt.Println(line1.Id)
		fmt.Println(line1.Content)
		fmt.Println(line1.Author)
		fmt.Println("------------")
	}
}
